package com.rh.number.controller;

import com.rh.number.common.ResponseResult;
import com.rh.number.common.Result;
import com.rh.number.dto.LoginRequest;
import com.rh.number.entity.UserinfoEntity;
import com.rh.number.mapper.UserinfoMapper;
import com.rh.number.service.AuthService;
import com.rh.number.util.JwtUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.MalformedJwtException;
import jakarta.validation.Valid;
import org.apache.tomcat.websocket.AuthenticationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;


import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/auth")
public class AuthController {

    private final AuthService authService;
    private final JwtUtil jwtUtil;
    private final UserinfoMapper userMapper;
    private final BCryptPasswordEncoder passwordEncoder;

    public AuthController(AuthService authService, JwtUtil jwtUtil, UserinfoMapper userMapper) {
        this.authService = authService;
        this.jwtUtil = jwtUtil;
        this.userMapper = userMapper;
        this.passwordEncoder = passwordEncoder(12);
    }

    private BCryptPasswordEncoder passwordEncoder(int i) {
        return new BCryptPasswordEncoder(i);
    }


    @PostMapping(value = "/login", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<ResponseResult<Map<String, Object>>> login(@RequestBody Map<String, String> params) {
        try {
            String username = params.get("username");
            String password = params.get("password");

            // 参数校验
            if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                        .body(ResponseResult.error(400, "用户名和密码不能为空"));
            }

            UserinfoEntity user = authService.authenticate(username, password);
            String token = jwtUtil.generateToken(user);

            return ResponseEntity.ok(
                    ResponseResult.success(user.toSafeMap(), token)
            );

        } catch (AuthenticationException ex) {
            // 认证失败处理
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                    .body(ResponseResult.error(401, "账号或密码错误"));
        } catch (Exception ex) {
            // 其他异常处理
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ResponseResult.error(500, "系统繁忙，请稍后重试"));
        }
    }

    @PostMapping(value = "/users", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Result<Void>> addUser( // 修改1：明确泛型类型
                                                 @RequestBody UserinfoEntity user,
                                                 @RequestAttribute(name = "role", required = false) Integer role) {

        try {
            // 保持原有业务逻辑
            if (user.getRole() == null) user.setRole(1);
            authService.addUser(user);

            // 修改2：避免返回null
            return ResponseEntity.ok(Result.success());
        } catch (RuntimeException e) {
            // 修改3：规范错误状态码
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(Result.fail(400, e.getMessage()));
        }
    }
    @PostMapping("/init")
    public ResponseEntity<?> initAdmin(@RequestBody UserinfoEntity user) {
        System.out.println("接收到初始化请求：" + user);
        // 检查是否已有用户
        if (userMapper.countUsers() > 0) {
            return ResponseEntity.status(403).body("系统已初始化");
        }
        if (user.getPassword() == null || user.getPassword().isBlank()) {
            return ResponseEntity.badRequest().body("密码不能为空");
        }

        // 创建初始管理员
        user.setRole(2);
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        userMapper.insert(user);

        return ResponseEntity.ok("管理员账户创建成功");
    }


    @GetMapping("/validate")
    public ResponseEntity<Result<Map<String, Object>>> validateToken(
            @RequestHeader(value = HttpHeaders.AUTHORIZATION, required = false) String authHeader) {

        // 1. 检查Authorization头格式
        if (!StringUtils.hasText(authHeader) || !authHeader.startsWith("Bearer ")) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                    .body(Result.error(401, "Authorization头格式错误"));
        }

        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(Result.error(400, "未提供有效令牌"));
        }

        // 2. 提取并验证Token
        String token = authHeader.substring(7);
        try {
            // 3. 执行深度验证
            Claims claims = jwtUtil.parseToken(token);

            // 4. 构造验证响应
            Map<String, Object> result = new HashMap<>();
            result.put("username", claims.getSubject());
            result.put("role", claims.get("role"));
            result.put("expiresAt", claims.getExpiration());

            return ResponseEntity.ok(Result.success(result));

        } catch (JwtException ex) {
            // 5. 处理具体JWT异常
            String errorMsg = "令牌验证失败: ";
            if (ex instanceof ExpiredJwtException) {
                errorMsg += "令牌已过期";
            } else if (ex instanceof MalformedJwtException) {
                errorMsg += "令牌格式错误";
            } else {
                errorMsg += ex.getMessage();
            }

            return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                    .body(Result.error(401, errorMsg));
        }
    }
}